import {
  Directive,
  Input,
  Output,
  EventEmitter,
  HostListener,
} from '@angular/core';

@Directive({
  selector: '[fuiFileDialog]',
})
export class FileDialogDirective {

  /** Existing file object. */
  @Input() fuiFileDialog: File;

  /** File format accept attribute. */
  @Input() fuiFileDialogAccept: string;

  /** Allow multipe files. */
  @Input() fuiFileDialogMultiple: boolean;

  /** Emit selected file. */
  @Output() fuiFileDialogChange = new EventEmitter<File>();

  @HostListener('click') onHostClick() {
    const input: HTMLInputElement = document.createElement('input');
    input.type = 'file';
    if (this.fuiFileDialogAccept) {
      input.accept = this.fuiFileDialogAccept;
    }
    if (this.fuiFileDialogMultiple) {
      input.multiple = true;
    }
    input.addEventListener('change', (event: any) => {
      const {files} = event.target;
      const file = input.multiple ? files : (files[0] ? files[0] : null);
      this.fuiFileDialogChange.emit(file);
    });
    input.click();
  }

  constructor() { }

}
